import { axhttp } from '@/shared/axhttp';
import { axurl } from '@/shared/axurl';

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    currentApp: {},
    otherApp: [],
    uploadInfo: {
      list: [],
      pagination: {},
    },
    downloadInfo: {
      list: [],
      pagination: {},
    },
  },
  effects: {
    /** 获取当前用户 */
    *fetchCurrent(_, { call, put }) {
      const response = yield call(axhttp.getFormData, axurl.resource.userInfo);
      if (response && response.success === true) {
        const user = response.list;
        localStorage.setItem('ax-data-user', JSON.stringify(user));
        yield put({
          type: 'saveCurrentUser',
          payload: response,
        });
      }
    },
    /** 获取其他应用 */
    *fetchOtherApp({ params }, { call, put }) {
      const response = yield call(axhttp.getFormData, axurl.resource.otherAppInfo, params);
      if (response && response.success === true) {
        const app = response.list;
        localStorage.setItem('ax-data-other', app.length);
        yield put({
          type: 'saveOtherApp',
          payload: response,
        });
      }
    },
    /** 获取上传信息 */
    *fetchUploadInfo({ params }, { call, put }) {
      const response = yield call(axhttp.getFormData, axurl.resource.uploadInfo, params);
      if (response && response.success === true) {
        yield put({
          type: 'saveUploadInfo',
          payload: response,
        });
      }
    },
    /** 获取下载信息 */
    *fetchDownloadInfo({ params }, { call, put }) {
      const response = yield call(axhttp.getFormData, axurl.resource.downloadInfo, params);
      if (response && response.success === true) {
        yield put({
          type: 'saveDownloadnfo',
          payload: response,
        });
      }
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload.list || {} };
    },
    saveCurrentApp(state, action) {
      return { ...state, currentApp: action.payload.list || {} };
    },
    saveOtherApp(state, action) {
      return { ...state, otherApp: action.payload.list || {} };
    },
    saveUploadInfo(state, action) {
      return { ...state, uploadInfo: action.payload || {} };
    },
    saveDownloadnfo(state, action) {
      return { ...state, downloadInfo: action.payload || {} };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
